
package org.vasil.jouikov.services

import groovy.xml.StreamingMarkupBuilder

class DataFeed {

    def parseFeed = { xml ->

        //println "xml:${xml}"
        def feed
        try {
            feed = new XmlSlurper().parseText(xml).declareNamespace(sc: 'http://schemas.google.com/structuredcontent/2009')
        }
        catch(error) {
            return ['status': 'Err', 'body': error]
        }
        //println "feed=${feed}"

        feed.link.each { link ->
            if(link.@rel.text() == 'next') {
                nextLink = link.@href.text()
            }
        }
        
        def sku, entities = [:]
        feed.entry.each { entry ->
            sku = entry.'sc:id'.text()

            entities[sku] = entry.'sc:expiration_date'.text()
        }
        //println "entities=${entities}"

	return ['status': 'Ok', 'next': nextLink, 'body': entities]
    }

    def makeBatch = { items ->

        def markupBuilder = new StreamingMarkupBuilder()
        markupBuilder.encoding = "UTF-8"

        def xml = markupBuilder.bind { builder ->
            mkp.xmlDeclaration()
            mkp.declareNamespace(''          : 'http://www.w3.org/2005/Atom')
            mkp.declareNamespace('openSearch': 'http://a9.com/-/spec/opensearch/1.1/')
            mkp.declareNamespace('app'       : 'http://www.w3.org/2007/app')
            mkp.declareNamespace('gd'        : 'http://schemas.google.com/g/2005')
            mkp.declareNamespace('sc'        : 'http://schemas.google.com/structuredcontent/2009')
            mkp.declareNamespace('scp'       : 'http://schemas.google.com/structuredcontent/2009/products')
            mkp.declareNamespace('batch'     : 'http://schemas.google.com/gdata/batch')

            feed {
                items.each { sku, item ->
                    out << getEntry(builder, sku, item, item.action['type']) // type == insert, update, query, delete
                }
            }
        }
        return xml
    }

    def getEntry = { builder, sku, item, type ->
 
        builder.entry {
            batch.operation(type: type)
            id("https://content.googleapis.com/content/v1/100115/items/products/generic/${sku}")

            if(type == 'insert' || type == 'update') {
                title(item.field.name)
                content(item.field.name)
                link(rel:'alternate',type:'text/html',href:"http://www.compuvest.com/Search.jsp?Search=${item.field.mfrnumber}&advsite=froogle&sku=${sku}&dp=${item.field.qty}:${item.field.vendorname}:${(item.field.reslprice.toDouble() * 100).round()}:${item.field.drone}:${item.field.older}")
                sc.id(sku)
                sc.image_link("http://img.compuvest.com/0/${sku}.jpg")
                sc.content_language('en')
                sc.target_country('US')
                scp.availability('in stock')
                scp.brand(item.field.mfrname)
                scp.condition(item.field.condition)
                scp.google_product_category(item.field.catname)
                scp.product_type(item.field.catname)
                scp.manufacturer(item.field.mfrname)
                scp.mpn(item.field.mfrnumber)
                scp.adwords_labels(item.field.accwareid)
                scp.adwords_grouping(item.field.googlegroup)
                scp.price(unit: 'USD', item.field.sellprice)
                if(item.field.upc != '0') {
                    scp.gtin(item.field.upc)
                }
                scp.quantity(item.field.qty)
                scp.shipping_weight(unit: 'LB', item.field.weight)
                scp.shipping {
                    scp.shipping_country('US')
                    scp.shipping_service('Shipping - Ground')
                    scp.shipping_price(unit: 'USD', '0.00')
                }
                scp.tax {
                    scp.tax_country('US')
                    scp.tax_region('WA')
                    scp.tax_rate('9.50')
                }
                app.control {
                    sc.required_destination('dest': 'Shopping')
                    sc.required_destination('dest': 'ProductSearch')
                }
            } // if
        }
    }

    def parseResult = { xml, items ->

        //println "\n>>>xml:\n${xml.toString()}"
        def result = 'Error'
        def feed
        try {
            feed = new XmlParser().parseText(xml.toString())
        }
        catch(e) {
            println ">>>>>>DataFeed::parseResult() Bad XML file <<<<<<xml=[${xml}]"
            return result
        }
        //println "feed=${feed}"

        def type, googleid, googlesku, item//, out = new StringBuilder()
        feed.entry.each { entry ->
            type = entry.'batch:operation'.@type[0]

            //out << "type=${type} "
            switch(type) {
                case 'insert':
                case 'update':
                case 'query':
                    googlesku = entry.'sc:id'.text()
                    break
                case 'delete':
                    googleid = entry.id.text()
                    googlesku = googleid[googleid.lastIndexOf('/') + 1..-1]
                    break
            } // switch

            //out << "googlesku=${googlesku} code=${entry.'batch:status'.@code[0]} reason=${entry.'batch:status'.@reason[0]}\n"
            result = "googlesku=${googlesku} code=${entry.'batch:status'.@code[0]} reason=${entry.'batch:status'.@reason[0]}"
            if(googlesku) {
                item = items[googlesku]
                item.status['code'] = entry.'batch:status'.@code[0]
                item.status['reason'] = entry.'batch:status'.@reason[0]
            }
        }
        //println out

        return result
    }

    def showResult = { items, count ->

        def result = [:], res = new StringBuilder()
        result['insert'] = 0
        result['update'] = 0
        result['delete'] = 0

        items.each { accwareid, item ->

            switch(item.action['type']) {
                case 'insert':
                    result['insert']++
                    break
                case 'update':
                    result['update']++
                    break
                case 'delete':
                    result['delete']++
                    break
            } // switch

            res << "<tr>"
            res << "<td>${count++}</td><td>${accwareid}</td><td>\$${item.field['oldreslprice']} : \$${item.field['reslprice']}</td>"
            res << "<td>\$${item.field['oldsellprice']} : \$${item.field['sellprice']}</td>"
            res << "<td>${item.action['type']}</td><td>${item.status['code']}</td><td>${item.status['reason']}</td><td>${item.status['accware']}</td>"
            res << "</tr>"
        }
        result['html'] = res.toString()

        return result
    }
}

